package com.soul.config;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoDatabaseFactorySupport;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.*;

/**
 * @description:
 * When using spring data mongo it by default adds a _class key to your collection to be able to handle inheritance.
 * But if your domain model is simple and flat, you can remove it by overriding the default MappingMongoConverter
 */
@Configuration
public class MongoConfiguration {
    // 通过自动注入来获取默认的配置类
    @Autowired
    private MongoDatabaseFactorySupport mongoDatabaseFactory;
    @Autowired
    private MappingMongoConverter mappingMongoConverter;

    //存数据的时候总是会存在一个多出来的字段_class。这个字段主要是为了在将Mongo的数据还原到Java的时候能找到对应的类
    //mongodb一般使用还是用类比sql的方式来操作，一个表存的就是一个实体。所以我就需要将这个字段删去，也是为了能够更好地兼容其他语言或环境
    @Bean
    public MongoTemplate mongoTemplate() {
        mappingMongoConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDatabaseFactory, mappingMongoConverter);
        return mongoTemplate;
    }
}
